package com.qk.manangement.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.common.context.UserContext;
import com.qk.common.response.BusinessGetByIdResponse;
import com.qk.common.response.BusinessPageResponse;
import com.qk.common.response.BusinessUpdateResponse;
import com.qk.common.response.PageResult;
import com.qk.entity.pojo.Business;
import com.qk.entity.pojo.BusinessTrackRecord;
import com.qk.entity.pojo.Customer;
import com.qk.entity.request.business.BusinessPageRequest;
import com.qk.entity.request.business.BusinessPoolRequest;
import com.qk.manangement.mapper.CustomerMapper;
import com.qk.manangement.service.BusinessService;
import com.qk.manangement.mapper.BusinessMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

/**
 *
 */
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business>
        implements BusinessService {
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private BusinessMapper businessMapper;

    @Override
    public PageResult pageList(BusinessPageRequest businessPageRequest) {
        // 参数校验
        if (ObjectUtil.isNull(businessPageRequest)) {
            return new PageResult(0L, new ArrayList<>());
        }

        // 设置分页参数
        PageHelper.startPage(businessPageRequest.getPage(), businessPageRequest.getPageSize());

        // 查询数据
        List<BusinessPageResponse> list = baseMapper.pageList(businessPageRequest);

        // 构建分页结果
        PageInfo<BusinessPageResponse> pageInfo = new PageInfo<>(list);
        return new PageResult(pageInfo.getTotal(), list);
    }


    @Override
    public boolean add(Business business) {
        if (ObjectUtil.isNull(business)) {
            return false;
        }

        if (StrUtil.isBlank(business.getPhone()) || ObjectUtil.isNull(business.getChannel())) {
            return false;
        }

        business.setStatus(1);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        return save(business);
    }


    @Override
    public boolean assign(Long businessId, Long userId) {
        if (ObjectUtil.isNull(businessId) || ObjectUtil.isNull(userId)) {
            return false;
        }

        return update(Wrappers.lambdaUpdate(Business.class)
                .set(Business::getUserId, userId)
                .set(Business::getUpdateTime, LocalDateTime.now())
                .set(Business::getStatus, 2)
                .eq(Business::getId, businessId)
        );
    }


    @Override
    public boolean back(Long id) {
        if (ObjectUtil.isNull(id)) {
            return false;
        }

        return update(Wrappers.lambdaUpdate(Business.class)
                .set(Business::getUpdateTime, LocalDateTime.now())
                .set(Business::getStatus, 4)
                .eq(Business::getId, id)
        );
    }


    @Override
    @Transactional
    public boolean toCustomer(Integer id) {
        // 参数校验
        if (ObjectUtil.isNull(id)) {
            return false;
        }

        // 获取商机信息
        Business business = getById(id);
        if (ObjectUtil.isNull(business) || StrUtil.isBlank(business.getName())) {
            return false;
        }

        // 创建客户信息
        Customer customer = new Customer();
        BeanUtil.copyProperties(business, customer, "id", "createTime", "updateTime");
        customer.setBusinessId(id);
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        customerMapper.insert(customer);

        // 更新商机状态
        return update(Wrappers.lambdaUpdate(Business.class)
                .set(Business::getStatus, 5)
                .eq(Business::getId, id)
        );
    }


    @Override
    public BusinessGetByIdResponse getBusinessById(Integer id) {
        if (ObjectUtil.isNull(id)) {
            return null;
        }
        return businessMapper.getBusinessById(id);
    }


    @Override
    @Transactional
    public boolean businessUpdate(BusinessUpdateResponse business) {
        // 参数校验
        if (ObjectUtil.isNull(business)) {
            return false;
        }

        // 业务必要字段校验
        if (ObjectUtil.isNull(business.getId()) ||
                StrUtil.isBlank(business.getPhone()) ||
                ObjectUtil.isNull(business.getChannel())) {
            return false;
        }

        // 更新 Business 实体
        Business updateBusiness = new Business();
        BeanUtil.copyProperties(business, updateBusiness);
        updateBusiness.setStatus(3);
        updateBusiness.setUpdateTime(LocalDateTime.now());
        updateBusiness.setUserId(UserContext.getUserId());
        this.updateById(updateBusiness);

        // 创建并保存跟踪记录
        BusinessTrackRecord businessTrackRecord = new BusinessTrackRecord();

        // 使用 StringJoiner 处理 keyItems（保持原有逻辑）
        StringJoiner stringJoiner = new StringJoiner(",", "[", "]");
        if (ObjectUtil.isNotEmpty(business.getKeyItems())) {
            for (String keyItem : business.getKeyItems()) {
                stringJoiner.add(keyItem);
            }
        }

        businessTrackRecord.setBusinessId(business.getId());
        businessTrackRecord.setUserId(UserContext.getUserId());
        businessTrackRecord.setTrackStatus(business.getTrackStatus());
        businessTrackRecord.setKeyItems(stringJoiner.toString());
        businessTrackRecord.setRecord(business.getRecord());
        businessTrackRecord.setNextTime(business.getNextTime());
        businessTrackRecord.setCreateTime(LocalDateTime.now());
        Db.save(businessTrackRecord);

        return true;
    }

    @Override
    public PageResult businessPoolList(BusinessPoolRequest businessPoolRequest) {
        // 参数校验
        if (ObjectUtil.isNull(businessPoolRequest)) {
            return new PageResult(0L, new ArrayList<>());
        }

        // 构建分页对象
        Page<Business> businessPage = new Page<>(businessPoolRequest.getPage(), businessPoolRequest.getPageSize());

        // 构建查询条件
        Page<Business> page = this.page(businessPage, Wrappers.lambdaQuery(Business.class)
                .eq(Business::getStatus, 4)
                .eq(ObjectUtil.isNotNull(businessPoolRequest.getBusinessId()), Business::getId, businessPoolRequest.getBusinessId())
                .like(StrUtil.isNotBlank(businessPoolRequest.getName()), Business::getName, businessPoolRequest.getName())
                .like(StrUtil.isNotBlank(businessPoolRequest.getPhone()), Business::getPhone, businessPoolRequest.getPhone())
                .like(ObjectUtil.isNotNull(businessPoolRequest.getSubject()), Business::getSubject, businessPoolRequest.getSubject())

        );

        // 返回分页结果
        return new PageResult(page.getTotal(), page.getRecords());
    }


}




